package com.jpro.framework.common.pojo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.math.MathUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Schema(description = "分页结果")
@Data
public final class PageResult<T> implements Serializable {

    @Schema(description = "数据", requiredMode = Schema.RequiredMode.REQUIRED)
    private List<T> list;

    @Schema(description = "总量", requiredMode = Schema.RequiredMode.REQUIRED)
    private Long total;

    @Schema(description = "总页数")
    private Long pages;

    @Schema(description = "当前页数")
    private Long current;

    public Long getTotalPages() {
        return pages;
    }

    /**
     * 管理后台不需要totalPages 参数，但是前台标签需要，如果使用Mybatisx 封装的查询需要分页参数需要主动设置page
     * @param pageParam
     */
    public void adjustPages(PageParam pageParam) {
        //只有未查询总页数的时候才手动设置
        if(pages==null&&pageParam!=null){
            if(CollUtil.isEmpty(list)||list.size()<pageParam.getPageSize()){
                setPages(1L);
            }else{
                final Double ceil = Math.ceil(total.doubleValue() / pageParam.getPageSize());
                setPages(ceil.longValue());
            }
        }
    }

    public boolean getHasPrevious() {
        if (ObjectUtils.isEmpty(current)) {
            return false;
        }
        return getCurrent() > 0;
    }

    public boolean getHasNext() {
        if (ObjectUtils.isEmpty(current)) {
            return false;
        }
        return getCurrent() + 1 < getTotalPages();
    }

    public PageResult() {
    }

    public PageResult(List<T> list, Long total) {
        this.list = list;
        this.total = total;
    }

    public PageResult(List<T> list, Long total, Long pages, Long current) {
        this.list = list;
        this.total = total;
        this.pages = pages;
        this.current = current;
    }

    public PageResult(Long total) {
        this.list = new ArrayList<>();
        this.total = total;
    }

    public static <T> PageResult<T> empty() {
        return new PageResult<>(0L);
    }

    public static <T> PageResult<T> empty(Long total) {
        return new PageResult<>(total);
    }

}
